#!/usr/bin/env python
# -*- coding: gb2312 -*-

import os
import errno
import time
import sys
import codecs
import getopt
import re

import myPopen,myUtf

PIPE = myPopen.PIPE
Popen = myPopen.Popen
message = "Other end disconnected!"

def recv_some(p, t=.1, e=1, tr=5, stderr=0):
    if tr < 1:
        tr = 1
    x = time.time()+t
    y = []
    r = ''
    pr = p.recv
    if stderr:
        pr = p.recv_err
    while time.time() < x or r:
        r = pr()
        if r is None:
            if e:
                raise Exception(message)
            else:
                break
        elif r:
            y.append(r)
        else:
            time.sleep(max((x-time.time())/tr, 0))
    return ''.join(y)
    
def send_all(p, data):
    while len(data):
        sent = p.send(data)
        if sent is None:
            raise Exception(message)
        data = buffer(data, sent)

def err_usage():
    print 'callmpl (list file to play)'
    sys.exit(-1)


oldstdin = sys.stdin
if __name__ == '__main__':
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'm:')
        for optpair in opts:  # like this[('-d', ''), ('-k', '3')...]
            if optpair[0]=='-m':
                try:
                    maxnum = int(optpair[1])
                except:
                    err_usage()
                    if maxnum ==-1:
                        print "can't be -1!"
                        sys.exit(1)

        a = Popen(['mplayer','-slave','-identify','-quiet','-playlist','playlist.m3u'],stdin=PIPE,stdout=PIPE,stderr=myPopen.STDOUT)

        fin = open('atom.xml','rb')
        unichar =  fin.read()
        fin.close()
        unirelt = myUtf.multdecode(unichar)
        print unirelt.encode('gb2312')
        if a.poll() == None:
            pass

    finally:
        sys.stdin = oldstdin

# check OSError exception
